//
//  WNViewedVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/7.
//

import UIKit

class WNViewedVC: WNBaseVC {
    
    lazy var viewedTabView: WNTableView = {
        let tab = WNTableView()
        tab.register(ViewedCell.self, forCellReuseIdentifier: ViewedCell.identifier)
        tab.delegate = self
        tab.dataSource = self
        tab.rowHeight = scaleWidth(90)+24
        tab.allowsMultipleSelectionDuringEditing = true
        tab.ly_emptyView = WNEmptyView.wn_loadStyle(descStr: .history, imageStr: .common, tapBlock: { [weak self] in
            tab.mj_header?.beginRefreshing()
        })
        tab.isHidden = true
        return tab
    }()
    
    lazy var deleteBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = .white
        btn.setTitle("刪除", for: .normal)
        btn.setTitle("刪除", for: .selected)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 16)
        btn.setTitleColor(.init(named: "gray_999999"), for: .normal)
        btn.setTitleColor(.init(named: "red_FE95B4"), for: .selected)
        btn.titleEdgeInsets = .init(top: 0, left: 0, bottom: TabBarMargin, right: 0)
        btn.rx.tap.bind { [weak self] in
            guard btn.isSelected else {
                return
            }
            showSpringType(.deleteViewedBook)
            WNSpringView.shared.isRightClosure = { isRight in
                if isRight {
                    self?.deleteViewedRequest()
                }
            }
        }.disposed(by: rx.disposeBag)
        btn.isHidden = true
        return btn
    }()
        
    var viewedArr = [BookDetailModel]()
    
    var selIndexArr = [Int]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        view.addSubview(viewedTabView)
        view.addSubview(deleteBtn)
        viewedTabView.snp.makeConstraints { make in
            make.top.equalTo(NaviTotalHeight)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarMargin)
        }
        deleteBtn.snp.makeConstraints { make in
            make.left.bottom.right.equalTo(0)
            make.height.equalTo(0)
        }
        deleteBtn.wn_cornerWithBorder(0, 0, .white, 1, .init(white: 0, alpha: 0.1), .init(width: 0, height: 1), 5)
        deleteBtn.layer.masksToBounds = false
    }
    
    override func dataConfig() {
        pageName = "閱讀歷史"
        navView.titleName = "閱讀歷史"
        navView.rightBtnImge = "book_more"
        navView.rightClosure = { [weak self] in
            self?.showMenu()
        }
        listSettingRefresh()
        viewdRequest()
    }
}

extension WNViewedVC {
    
    func showMenu() {
        guard viewedArr.count > 0 else { return }
        if viewedTabView.isEditing {
            selIndexArr.removeAll()
            deleteBtn.isHidden = true
            deleteBtn.isSelected = false
            deleteBtn.snp.updateConstraints { make in
                make.height.equalTo(0)
            }
            viewedTabView.setEditing(false, animated: true)
            navView.rightBtnImge = "book_more"
            view.layoutIfNeeded()
        }else {
            let popMenu = SwiftPopMenu(menuWidth: 100, arrow: .zero, datas: ["全部刪除", "選擇"])
            popMenu.didSelectMenuBlock = { [weak self] index in
                if index == 0 {
                    showSpringType(.deleteAllViewedBook)
                    WNSpringView.shared.isRightClosure = { isRight in
                        if isRight {
                            self?.deleteViewedRequest(true)
                        }
                    }
                }else {
                    self?.deleteBtn.isHidden = false
                    self?.viewedTabView.setEditing(true, animated: true)
                    self?.navView.rightBtnTitle = "取消"
                    self?.deleteBtn.snp.updateConstraints { make in
                        make.height.equalTo(TabBarTotalHeight)
                    }
                    self?.view.layoutIfNeeded()
                }
                popMenu.dismiss()
            }
            popMenu.arrowPoint = .init(x: navView.rightBtn.right-26, y: navView.rightBtn.bottom)
            popMenu.show()
        }
    }
    
    func listSettingRefresh() {
        viewedTabView.mj_header = wn_refreshHeader(completion: { [weak self] in
            if (self?.viewedTabView.isEditing ?? true) {
                self?.viewedTabView.mj_header?.endRefreshing()
                return
            }
            self?.page = 1
            self?.hasPage = false
            self?.viewdRequest()
        })
        
        viewedTabView.mj_footer = wn_refreshFooter(completion: { [weak self] in
            if (self?.viewedTabView.isEditing ?? true) {
                self?.viewedTabView.mj_footer?.endRefreshing()
                return
            }
            if self?.page == 1 && (self?.viewedArr.count ?? 0) == 0 {
                self?.viewedTabView.mj_footer?.endRefreshing()
                return
            }
            if self?.hasPage == true {
                self?.page += 1
                self?.viewdRequest()
            }else {
                self?.viewedTabView.mj_footer?.endRefreshingWithNoMoreData()
            }
        })
    }
    
    func handleDeleteBtn() {
        if let items = viewedTabView.indexPathsForSelectedRows, items.count > 0 {
            deleteBtn.isSelected = true
            deleteBtn.setTitle(("刪除(\(items.count))"), for: .selected)
        }else {
            deleteBtn.isSelected = false
        }
    }
    
    func deleteItems(_ isAll: Bool = false) {
        if isAll {
            viewedArr.removeAll()
            viewedTabView.reloadData()
        }else {
            selIndexArr.removeAll()
            if let selectedItems = viewedTabView.indexPathsForSelectedRows {
                for indexPath in selectedItems {
                    selIndexArr.append(indexPath.item)
                }
            }
            if selIndexArr.count != 0 {
                viewedArr.removeAt(indexes: selIndexArr)
                viewedTabView.reloadData()
            }
        }
        showMenu()
    }
}

extension WNViewedVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        viewedArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ViewedCell.identifier, for: indexPath) as! ViewedCell
        cell.model = viewedArr[indexPath.item]
        cell.lineView.isHidden = indexPath.item == (viewedArr.count - 1)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if !tableView.isEditing {
            wn_pushBookVC(viewedArr[indexPath.item].bookId ?? "")
        }else {
            handleDeleteBtn()
        }
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        handleDeleteBtn()
    }
}

extension WNViewedVC {
    
    func viewdRequest() {
        provider_setting.rx.request(.viewedList(page))
            .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                self?.viewedTabView.isHidden = false
                self?.viewedTabView.ly_emptyView.imageStr = EmptyImage.common.rawValue
                self?.viewedTabView.ly_emptyView.detailStr = EmptyDesc.history.rawValue
                self?.viewedTabView.ly_emptyView.btnTitleStr = ""
                guard model.code == 0 else {
                    if (self?.isFirst ?? true) {
                        self?.viewedTabView.ly_emptyView.imageStr = EmptyImage.serverBad.rawValue
                        self?.viewedTabView.ly_emptyView.detailStr = EmptyDesc.serverBad.rawValue
                        self?.viewedTabView.ly_emptyView.btnTitleStr = "點擊刷新"
                    }else {
                        self?.wn_toast(model.msg ?? "")
                    }
                    self?.viewedTabView.mj_header?.endRefreshing()
                    self?.viewedTabView.mj_footer?.endRefreshing()
                    self?.isFirst = false
                    return
                }
                if self?.page == 1 {
                    self?.viewedArr.removeAll()
                    self?.viewedTabView.mj_footer?.resetNoMoreData()
                }
                if let arr = model.data {
                    self?.hasPage = arr.count > 9
                    self?.viewedArr += arr
                }else {
                    self?.viewedTabView.mj_footer?.endRefreshingWithNoMoreData()
                }
                self?.viewedTabView.reloadData()
                self?.viewedTabView.mj_header?.endRefreshing()
                self?.viewedTabView.mj_footer?.endRefreshing()
                self?.isFirst = false
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
                self?.viewedTabView.ly_emptyView.imageStr = EmptyImage.netWork.rawValue
                self?.viewedTabView.ly_emptyView.detailStr = EmptyDesc.netWork.rawValue
                self?.viewedTabView.ly_emptyView.btnTitleStr = "點擊刷新"
                self?.viewedTabView.mj_header?.endRefreshing()
                self?.viewedTabView.mj_footer?.endRefreshing()
                self?.viewedTabView.isHidden = false
            }).disposed(by: rx.disposeBag)
    }
    
    
    func deleteViewedRequest(_ isAll: Bool = false) {
        var bookIds = [String]()
        if isAll {
            for item in viewedArr {
                bookIds.append(item.bookId ?? "")
            }
        }else {
            if let selectedItems = viewedTabView.indexPathsForSelectedRows {
                for indexPath in selectedItems {
                    bookIds.append(viewedArr[indexPath.item].bookId ?? "")
                }
            }
        }
        guard bookIds.count > 0 else { return }
        provider_setting.rx.request(.viewedDelete(bookIds.joined(separator: ",")))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if model.data != nil {
                    self?.wn_toast("刪除成功")
                    self?.deleteItems(isAll)
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
}
